package com.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.entity.BanJi;
import com.example.entity.User;
import com.example.entity.XueYuan;
import com.example.service.BanJiService;
import com.example.service.RoleService;
import com.example.service.UserService;
import com.example.service.XueYuanService;
import com.example.vo.DataView;
import com.example.vo.UserVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private BanJiService banJiService;
    @Autowired
    private XueYuanService xueYuanService;
    @Autowired
    private RoleService roleService;

    @RequestMapping("/loadAllUser")
    public DataView loadAllUser(UserVo userVo){
        IPage<User> page=new Page<>(userVo.getPage(), userVo.getLimit());
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(userVo.getUsername()),"username",userVo.getUsername());
        queryWrapper.eq(StringUtils.isNotBlank(userVo.getPhone()),"phone",userVo.getPhone());
        IPage<User> iPage = userService.page(page, queryWrapper);
        //通过外键拿到名字
        // 注意：这种方式要查很多次库，效率很低，可以自己写一个方法表连接查询@Select
        // select a.username, b.name
        // from user a where a.username= #{userVo.getUsername}
        // left join ban_ji b
        // on a.ban_ji_id = b.id
        // limit #{iPage.getTotal()},#{iPage.getRecords()}
        for (User user: iPage.getRecords()){
            if(user.getBanJiId()!=null){
                BanJi banJi = banJiService.getById(user.getBanJiId());
                user.setBanJiName(banJi.getName());
            }
            if (user.getXueYuanId()!=null){
                XueYuan xueYuan = xueYuanService.getById(user.getXueYuanId());
                user.setXueYuanName(xueYuan.getName());
            }
            if (user.getTeacherId()!=null){
                User teacher = userService.getById(user.getTeacherId());
                user.setTeacherName(teacher.getUsername());
            }
        }

        return new DataView(iPage.getTotal(),iPage.getRecords());
    }


    /**
     * 新增或更新用户
     */
    @RequestMapping({"/addUser","/updateUser"})
    public DataView addUser(User user){
        boolean save = userService.saveOrUpdate(user);
        DataView dataView=new DataView();
        dataView.setCode(200);
        dataView.setMsg("新增或更新用户成功");
        return dataView;
    }

    /**
     * 删除用户
     */
    @RequestMapping("/deleteUser/{id}")
    public DataView deleteUser(@PathVariable("id") Integer id){
        userService.removeById(id);
        DataView dataView=new DataView();
        dataView.setCode(200);
        dataView.setMsg("删除用户成功");
        return dataView;
    }

    /**
     * 初始化下拉列表的数据【班级】
     */
    @RequestMapping("/listAllBanJi")
    public List<BanJi> listAllBanJi(){
        List<BanJi> list = banJiService.list();
        return list;
    }

    /**
     * 初始化下拉列表的数据【学院】
     */
    @RequestMapping("/listAllXueYuan")
    public List<XueYuan> listAllXueYuan(){
        List<XueYuan> list = xueYuanService.list();
        return list;
    }

    /**
     * 重置密码
     */
    @RequestMapping("/resetPwd/{id}")
    public DataView resetPwd(@PathVariable("id") Integer id){
        User user=new User();
        user.setId(id);
        user.setPassword("123456");
        userService.updateById(user);
        DataView dataView=new DataView();
        dataView.setCode(200);
        dataView.setMsg("用户重置密码成功");
        return dataView;
    }

    /**
     * 点击分配的时候 初始化用户角色
     */
    @RequestMapping("/initRoleByUserId")
    public DataView initRoleByUserId(Integer id){
        List<Map<String, Object>> listMaps = roleService.listMaps();
        List<Integer> currentUserRoleIds = roleService.queryUserRoleById(id);
        for (Map<String,Object> map:listMaps){
            Boolean LAY_CHECKED=false;
            Integer roleId = (Integer) map.get("id");
            for (Integer rid:currentUserRoleIds){
                if(roleId.equals(rid)){
                    LAY_CHECKED=true;
                    break;
                }
            }
            map.put("LAY_CHECKED",LAY_CHECKED); //layui就是这样定义的，必须是这个属性
        }
        return  new DataView(Long.valueOf(listMaps.size()),listMaps);
    }


    /**
     * 保存用户与角色之间的关系 1：n
     * @return
     */
    @RequestMapping("/saveUserRole")
    public DataView saveUserRole(Integer uid,Integer[] ids){
        userService.saveUserRole(uid,ids);
        DataView dataView=new DataView();
        dataView.setCode(200);
        dataView.setMsg("角色分配成功");
        return dataView;
    }

}
